﻿<%@ WebHandler Language="C#" Class="SIPO.Web.AjaxHandler.Transaction.recPaymentVerificationhandler" %>

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;

using SIPO.Library.DataAccess.Transaction;
using SIPO.Library.DomainObject.Transaction;
using SIPO.Library.DataAccess.Administration;
using SIPO.Library.DomainObject.Administration;

using SIPO.Library.DomainObject.Administration.Catalog;
using SIPO.Library.DataAccess.Administration.Catalog;

using SIPO.Library.Enum;
using SIPO.Web.Support;

using Newtonsoft.Json.Linq;
using System.Web.SessionState;

namespace SIPO.Web.AjaxHandler.Transaction
{
    public class recPaymentVerificationhandler : SIPO.Web.BaseHandler
    {
        private recPaymentRepo repo =
            new recPaymentRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private recLogRepo logDal = new recLogRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private string MethodName = string.Empty;
        
        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            MethodName = context.Request.Params["method"];

            context.Response.Clear();
            context.Response.Buffer = true;

            System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);

            string jsonString = string.Empty;
            jsonString = context.Server.UrlDecode(sr.ReadToEnd());
            JObject jObj = string.IsNullOrEmpty(jsonString) ? null : JObject.Parse(jsonString);

            sr.Close();
            sr.Dispose();

            switch (MethodName.ToLower())
            {
                case ("verify"):
                    context.Response.Write(Verify(context, jObj));
                    break;
                case ("getdata"):
                    context.Response.Write(GetData(context));
                    break;
                default:
                    // do nothing
                    break;
            }
        }

        private string Verify(HttpContext context, JObject jo) {

            
            string a = context.Request.QueryString["param"];
            System.Collections.Generic.List <string> x = new List<string>();
                x = a.Split(',').ToList<string>();
                System.Collections.Generic.List<string> InvoiceSucess = new List<string>();
                InvoiceSucess = repo.UpdateUnverifiedPayment(x);


                var gridData = new
                {
                    page = "",
                    total = x.Count,
                    records = InvoiceSucess.Count,
                    rows = x.Count,
                };

                return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);
            
        }

        private string GetData(HttpContext context)
        {
            string parameters = Helper.JqGridFilterToSQLParams(context);

            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? recRestructur.Fields.RestructurID : context.Request.QueryString["sidx"].ToString());

            switch (sidx)
            { 
                case "NamaPerusahaan" :
                    { 
                    sidx = "master.recDebtor.DebtorName";
                        break;
                    }
                case "Sektor":
                    {
                        sidx = "master.recSector.SectorName";
                        break;
                    }
                case "NoInvoice":
                    {
                        sidx = "transactions.recInvoice.InvoiceNo";
                        break;
                    }
                case "JumlahTagihan":
                    {
                        sidx = "transactions.recInvoice.InvoiceValue";
                        break;
                    }
                case "IDTransaksi":
                    {
                        sidx = "transactions.recPayment.PaymentNo";
                        
                        break;
                    }
                case "JumlahPembayaran":
                {
                    sidx = "transactions.recPayment.PaymentValue";
                    break;
                }
                case "TanggalJatuhTempo":
                {
                    sidx = "transactions.recBilling.DueDate";
                    break;
                }
                default : 
                        {
                            sidx = "master.recDebtor.DebtorName";
                        break;
                        }
                     
            }
            
            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            int totalCount = 0;
            int totalPages = 0;
            List<UnVerifiedPaymentDTO> pagedList = new List<UnVerifiedPaymentDTO>();

            try
            {
                totalCount = Convert.ToInt32(repo.SelectScalarListUnverifiedPayment(SQL.Function.Aggregate.Count, "recPayment.PaymentNo", parameters));

                decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                totalPages = Convert.ToInt32(dc);

                DataTable DataTable = new System.Data.DataTable();
                DataTable = repo.ListUnverifiedPayment(pageSize, page, sidx, sord, parameters);
                UnVerifiedPaymentDTO UnVerifiedPaymentDTO;
                foreach (DataRow dr in DataTable.Rows)
                {
                    UnVerifiedPaymentDTO = new Support.UnVerifiedPaymentDTO();
                   
                    UnVerifiedPaymentDTO.No = dr[0] == DBNull.Value ? 0 : int.Parse(dr[0].ToString());
                        UnVerifiedPaymentDTO._DebtorID = dr["_DebtorID"] == DBNull.Value ? 0 : int.Parse(dr["_DebtorID"].ToString());
                        UnVerifiedPaymentDTO.NamaPerusahaan = dr["NamaPerusahaan"] == DBNull.Value ? "" : dr["NamaPerusahaan"].ToString();
                        UnVerifiedPaymentDTO._SectorID   = dr["_SectorID"] == DBNull.Value ? 0 : int.Parse(dr["_SectorID"].ToString());
                        UnVerifiedPaymentDTO.NamaSector = dr["NamaSector"] == DBNull.Value ? "" : dr["NamaSector"].ToString();
                        UnVerifiedPaymentDTO.NoInvoice = dr["NoInvoice"] == DBNull.Value ? "" : dr["NoInvoice"].ToString();
                        UnVerifiedPaymentDTO.JumlahTagihan = dr["JumlahTagihan"] == DBNull.Value ? 0 : decimal.Parse(dr["JumlahTagihan"].ToString());
                        UnVerifiedPaymentDTO.IDTransaksi = dr["IDTransaksi"] == DBNull.Value ? "" : dr["IDTransaksi"].ToString();
                        UnVerifiedPaymentDTO.JumlahPembayaran = dr["JumlahPembayaran"] == DBNull.Value ? 0 : decimal.Parse(dr["JumlahPembayaran"].ToString());
                        UnVerifiedPaymentDTO.TanggalJatuhTempo = dr["TanggalJatuhTempo"] == DBNull.Value ? DateTime.Now : DateTime.Parse(dr["TanggalJatuhTempo"].ToString());
                    
                    
                    pagedList.Add(UnVerifiedPaymentDTO);
                }
                
                //pagedList = null;

                //List<UnVerifiedPaymentDTO> pgEx =
                //    pagedList.Select(x=> new UnVerifiedPaymentDTO() { 
                //        _DebtorID = x.
                //    }).ToList<UnVerifiedPaymentDTO>();
            }
            catch (Exception ex)
            {
                recLog log = new recLog();
                log.LogEvent = "GetData";
                log.LogMessage = ex.Message;
                log.LogSource = "recPaymentVerification.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            finally
            {

            }

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,
            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);

        }
    }
}